package ru.kest.babymonitor.service.audio;

import ru.kest.babymonitor.Settings;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * AudioQueue is responsible for communication between http stream reader and listener of audio data
 */
public class AudioQueue {

    private static String TAG = "IPCamBabyMonitorService";

    private static int MAX_QUEUE_LENGTH = 10;

    Settings settings = Settings.getInstance();
    private static AudioQueue instance;

    private static BlockingQueue<short[]> audioQueue = new LinkedBlockingQueue<short[]>(MAX_QUEUE_LENGTH);
    private static BlockingQueue<short[]> analyzeQueue = new LinkedBlockingQueue<short[]>(MAX_QUEUE_LENGTH);

    private AudioQueue() { }

    public static synchronized AudioQueue getInstance() {
        if (instance == null) {
            instance = new AudioQueue();
        }
        return instance;
    }

    public void put(short[] buf) {
//        if (settings.isAudioOn() || settings.isAudioOnAlarmOn()) {
            if (!audioQueue.offer(buf)) {
                //            Log.i(TAG, "AudioQueue if full (nobody listen it?). Queue len: " + audioQueue.size());
                audioQueue.poll();
                audioQueue.add(buf);
            }
//        }
        if (settings.isAlarmOn()) {
            if (!analyzeQueue.offer(buf)) {
                analyzeQueue.poll();
                analyzeQueue.add(buf);
            }
        }
    }

    public short[] getAudioData() throws InterruptedException {
        return audioQueue.take();
    }

    public short[] getAudioData(int timeout) throws InterruptedException {
        return audioQueue.poll(timeout, TimeUnit.MILLISECONDS);
    }

    public short[] getDataForAnalysis() throws InterruptedException {
        return analyzeQueue.take();
    }

    public void clear() {
        audioQueue.clear();
        analyzeQueue.clear();
    }
}
